<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <div v-if="addEditFlag == 'add' || addEditFlag == 'edit'">
                <!-- <el-form-item label="角色类型" prop="roleType">
                    <el-select v-model="ruleForm.roleType" class="w100p" clearable filterable placeholder="请选择角色类型">
                        <el-option v-for="item, index in roleList" :label="item.name" :value="item.type"
                            :key="index"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="权限等级" prop="privilegeLevel">
                    <el-input class="w100p" type="number" v-model="ruleForm.privilegeLevel"
                        placeholder="请输入权限等级"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName">
                    <el-input class="w100p" v-model="ruleForm.realName" placeholder="请输入真实姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNo">
                    <el-input class="w100p" v-model="ruleForm.phoneNo" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="账号" prop="userName" v-if="roleType == 'ADMINISTRATOR'">
                    <el-input class="w100p" v-model="ruleForm.userName" placeholder="请输入账号"></el-input>
                </el-form-item>
                <el-form-item label="密码" v-if="!(addEditFlag == 'edit')" prop="password">
                    <el-input class="w100p" show-password v-model="ruleForm.password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" v-if="!(addEditFlag == 'edit')" prop="confirmPassword">
                    <el-input class="w100p" show-password v-model="ruleForm.confirmPassword"
                        placeholder="请确认密码"></el-input>
                </el-form-item>
            </div>
            <div v-else class="w100p roleData">
                <div class="roleTree">
                    <div class="menuTitle">菜单列表</div>
                    <el-tree ref="tree" :check-strictly="true" show-checkbox @check-change="handleCheckChange"
                        :data="roledata" node-key="functionPermissionId" default-expand-all
                        :expand-on-click-node="false" :props="{ children: 'child' }">
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                            <span>{{ data.funcName }}</span>
                        </span>
                    </el-tree>
                </div>
            </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>

import webUser from "@/api/webUser";
import functionPermissionApi from "@/api/functionPermission"
export default {
    components: {},
    props: {
        roleType: {
            type: String,
            default: () => {
                return 'AGENT'
            }
        },
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        }
    },
    data() {
        var validatePhone = (rule, value, callback) => {
            const reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; // 手机号正则表达式  
            if (value === '') {
                callback(new Error('请输入手机号'));
            } else if (!reg.test(value)) {
                callback(new Error('请输入正确的手机号'));
            } else {
                callback();
            }
        };
        var validatePassword = (rule, value, callback) => {
            if (!value || value.length < 6) {
                callback(new Error('请输入至少6位的密码'));
            } else {
                callback();
            }
        };
        var validateConfirmPassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请再次输入密码'));
            } else if (this.ruleForm.password && this.ruleForm.password !== value) {
                callback(new Error('两次输入密码不一致'));
            } else {
                callback();
            }
        };
        return {
            roledata: [],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            allRoleList: [],
            roleList: [
                {
                    type: 'ADMINISTRATOR',
                    name: '后台管理员'
                }, {
                    type: 'AGENT',
                    name: 'APP用户'
                },
            ],
            addEditName: '添加',
            addEditApi: webUser.add,
            ruleForm: {},
            rules: {
                password: [
                    { required: true, validator: validatePassword, trigger: 'change' }
                ],
                confirmPassword: [
                    { required: true, validator: validateConfirmPassword, trigger: 'change' }
                ],
                phoneNo: [
                    { required: true, validator: validatePhone, trigger: 'change' }
                ],
                realName: [
                    { required: true, message: '请输入真实姓名', trigger: 'change' }
                ],
                roleType: [
                    { required: true, message: '请选择角色类型', trigger: 'change' }
                ],
                userName: [
                    { required: true, message: '请输入账号', trigger: 'change' }
                ]
            }
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },
    computed: {},
    mounted() {
        this.queryTableList();
        this.queryRoleList();
    },
    methods: {
        handleCheckChange(data, checked, indeterminate) {
            let funcIdList = this.$refs.tree.getCheckedKeys()
            if (data.pId) {
                let list = [];
                let funclist = [];
                this.allRoleList.forEach(e => {
                    let hasId = funcIdList.includes(e.functionPermissionId)
                    if (hasId && e.pId) {
                        list.push(e)
                        let rut_1 = this.allRoleList.find(a => a.functionPermissionId == e.pId);
                        let rut_2 = list.find(a => a.functionPermissionId == e.pId);
                        if (rut_1 && !rut_2) {
                            list.push(rut_1)
                        }
                    }
                })

                funclist = list.filter(e => {
                    if (!e.pId) {
                        let rut_1 = list.find(a => a.pId == e.functionPermissionId);
                        return !!rut_1
                    } else {
                        return true
                    }
                })
                this.ruleForm.funcIdList = Array.from(new Set(funclist.map(e => e.functionPermissionId)))
                this.$refs.tree.setCheckedKeys(this.ruleForm.funcIdList);
            } else {
                if (!checked) {
                    let filterList = this.allRoleList.filter(e => e.pId == data.functionPermissionId);
                    let filterFuncIdList = filterList.map(e => e.functionPermissionId)
                    funcIdList = funcIdList.filter(e => !filterFuncIdList.includes(e))
                    this.$refs.tree.setCheckedKeys(funcIdList);
                    console.log(funcIdList)
                }
            }
        },
        async queryRoleList() {
            let { data: allRoleList } = await functionPermissionApi.queryList({});
            this.allRoleList = allRoleList
        },
        queryTableList() {
            this.loading = true;
            functionPermissionApi.queryTree({}).then(res => {
                this.loading = false;
                let { data } = res
                this.roledata = data || []
            }).catch(err => {
                this.loading = false;
                console.log(err)
            })
        },
        async initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm();
                this.addEditApi = webUser.add;
                this.addEditName = '添加';
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data };
                this.addEditApi = webUser.edit;
                this.addEditName = '编辑';
            } else if (this.addEditFlag == 'role') {
                this.ruleForm = {
                    userId: this.data.userId,
                    funcIdList: []
                };
                let { data: roleList } = await webUser.queryUserFuncList(this.data.userId);
                let roleIdList = (roleList || []).map(e => e.functionPermissionId)
                console.log(roleList, roleIdList)
                this.$refs.tree.setCheckedKeys(roleIdList);
                this.addEditApi = webUser.addFuncList;
                this.addEditName = '配置权限';
            }
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (this.addEditFlag == 'add') {
                        this.ruleForm.accountStatus = true;
                    }
                    this.addEditApi({
                        ...this.ruleForm,
                        roleType: this.roleType
                    }).then(res => {
                        console.log(res)
                        let { msg, code } = res;
                        if (code == 1) {
                            this.cancel()
                            this.$message.success('操作成功')
                        } else {
                            this.$message.error(msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.warning('操作失败')
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.line {
    border-bottom: 1px solid #e6e6e6;
}

.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item {
        .label {
            display: none;
        }

        .el-form-item__content {
            margin: 0;
        }
    }
}

.roleData {
    width: 100%;

    .roleTree {
        width: 100%;
        padding: 10px;
        background-color: #f3f3f3;
    }

    .menuTitle {
        margin-bottom: 20px;
    }
}
</style>